package com.smt.take.ui.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.os.SystemClock
import android.text.TextUtils
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import cn.smssdk.EventHandler
import cn.smssdk.SMSSDK
import com.smt.take.R
import com.smt.take.model.beans.UserBean
import com.smt.take.presenter.LoginActivityPresenter
import com.smt.take.utils.SMSUtil
import kotlinx.android.synthetic.main.activity_login.*
import org.jetbrains.anko.toast

class LoginActivity : AppCompatActivity() {

    private var time = 60
    lateinit var presenter: LoginActivityPresenter

    companion object {
        const val TIME_MINUS = -1
        const val TIME_IS_OUT = 0
    }

    private var eventHandler: EventHandler = object : EventHandler() {
        override fun afterEvent(event: Int, result: Int, data: Any) {
            if (data is Throwable) {
                Log.e("sms", data.message.toString())
            } else {
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //短信验证码回调完成
                    when (event) {
                        SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE -> {
                            //提交验证码成功
                            Log.e("sms", "提交验证码成功${data}")
                            val phone = et_user_phone.text.toString().trim()
                            presenter.loginByPhone(phone)
                        }
                        SMSSDK.EVENT_GET_VERIFICATION_CODE -> {
                            //获取验证码成功
                            Log.e("sms", "获取验证码成功${data}")
                        }
                        SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES -> {
                            //返回支持发送验证码的国家列表
                        }
                    }
                } else {
                    (data as Throwable).printStackTrace()
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        presenter = LoginActivityPresenter(this)
        initListener()
        //注册一个事件回调监听，用于处理SMSSDK接口请求的结果
        SMSSDK.registerEventHandler(eventHandler)
    }

    private fun initListener() {

        iv_user_back.setOnClickListener { finish() }
        tv_user_code.setOnClickListener {
            val phone = et_user_phone.text.toString().trim()
            if (SMSUtil.judgePhoneNum(this, phone)) {
                // 请求验证码，其中country表示国家代码，如“86”；phone表示手机号码，如“13800138000”
                //SMSSDK.getVerificationCode("86", phone)

                // 开启倒计时
                tv_user_code.isEnabled = false
                Thread(CutDownTask()).start()
            }

        }
        iv_login.setOnClickListener {
            val phone = et_user_phone.text.toString().trim()
            val code = et_user_code.text.toString().trim()
//            if (SMSUtil.judgePhoneNum(this, phone) && !TextUtils.isEmpty(code)) {
//                // 提交验证码，其中的code表示验证码，如“1357”
//               SMSSDK.submitVerificationCode("86", phone, code)
//            }
            presenter.loginByPhone(phone)
        }
    }

    // 使用完EventHandler需注销，否则可能出现内存泄漏
    override fun onDestroy() {
        super.onDestroy()
        SMSSDK.unregisterEventHandler(eventHandler)
    }


    val handler = @SuppressLint("HandlerLeak") object : Handler() {
        @SuppressLint("SetTextI18n")
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                TIME_MINUS -> tv_user_code.text = "剩余时间(${time})秒"
                TIME_IS_OUT -> {
                    tv_user_code.isEnabled = true
                    tv_user_code.text = "重新发送"
                    time = 60
                }
            }
        }
    }

    inner class CutDownTask : Runnable {
        override fun run() {
            while (time > 0) {
                // 刷新剩余时间，当前子线程，使用handler
                handler.sendEmptyMessage(TIME_MINUS)
                SystemClock.sleep(999)
                time--
            }
            handler.sendEmptyMessage(TIME_IS_OUT)
        }
    }

    fun onHomeSuccess(data: UserBean) {
        finish()
        toast("登陆成功")
    }

    fun onHomeFailed() {
        toast("登陆失败")
    }
}
